package com.gg.registration.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gg.common.helper.HttpRequestHelper;
import com.gg.common.result.ResultCodeEnum;
import com.gg.common.utils.RegistrationException;
import com.gg.registration.enums.OrderStatusEnum;
import com.gg.registration.enums.PaymentStatusEnum;
import com.gg.registration.model.order.OrderInfo;
import com.gg.registration.model.order.PaymentInfo;
import com.gg.registration.order.feignClient.HospitalFeignClient;
import com.gg.registration.order.mapper.PaymentInfoMapper;
import com.gg.registration.order.service.OrderService;
import com.gg.registration.order.service.PaymentInfoService;
import com.gg.registration.order.service.RefundInfoService;
import com.gg.registration.vo.order.SignInfoVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Author：  chenjunjia
 * Date：    2022/4/27 21:17
 * WeChat：  China_JoJo_
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private HospitalFeignClient hospitalFeignClient;

//    @Resource
//    private OrderService orderService;

    private OrderServiceImpl orderService = new OrderServiceImpl();


    /**
     * 保存交易记录
     * @param orderInfo 订单号
     * @param type 支付类型（1：微信支付 2：支付宝）
     */
    @Override
    public void savePaymentInfo(OrderInfo orderInfo, Integer type) {
        //根据订单号和交易类型先查询，若有则返回
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",orderInfo.getId())
                .eq("payment_type",type);
        PaymentInfo paymentInfo = baseMapper.selectOne(wrapper);
        if (null!=paymentInfo) {
            return;
        }
        //否则保存交易记录
        paymentInfo = new PaymentInfo();
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(type);
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")+"|"+orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle();
        paymentInfo.setSubject(subject);
        paymentInfo.setTotalAmount(orderInfo.getAmount());
        baseMapper.insert(paymentInfo);
    }

    @Override
    public void paySuccess(String outTradeNo, Integer type, Map<String, String> resultMap) {
        //根据订单号和交易类型先查询，若有则返回
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("out_trade_no",outTradeNo)
                .eq("payment_type",type);
        PaymentInfo paymentInfo = baseMapper.selectOne(wrapper);
        if (null == paymentInfo) {
            throw new RegistrationException(ResultCodeEnum.PARAM_ERROR);
        }
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        paymentInfo.setTradeNo(resultMap.get("transaction_id"));
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(resultMap.toString());
        //修改消费记录
        baseMapper.updateById(paymentInfo);
        //修改订单
        OrderInfo orderInfo = orderService.getById(paymentInfo.getOrderId());
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        orderService.updateById(orderInfo);

        // TODO 调用医院方接口，修改医院方订单
        //以后肯定是用feign的
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if(null == signInfoVo) {
            throw new RegistrationException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl()+"/order/updatePayStatus");

        //删除redis的key
        redisTemplate.delete("com.gg.registration.order.service.WechatPayService.createNative.orderId:"+orderInfo.getId());
    }

    /**
     * 获取消费记录
     * @param orderId
     * @param paymentType
     * @return
     */
    @Override
    public PaymentInfo getPaymentInfo(Long orderId, Integer paymentType) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        queryWrapper.eq("payment_type", paymentType);
        return baseMapper.selectOne(queryWrapper);
    }
}
